import QtQuick 2.15
import QtQuick.Controls 2.15

// 热力图组件
// 功能：点击添加热点，使用径向渐变绘制热力图
Item {
    id: root
    
    width: 1600
    height: 1200
    
    property int radius: 80  // 热点半径
    property int heatAlpha: 200  // 热力图整体透明度 [0-255]
    
    // 热点数据结构
    property var points: []  // [{x, y, radius, count}]
    property int maxCount: 1  // 最大权重
    
    // 颜色表（256个颜色值，对应alpha值0-255）
    property var colorList: []
    
    // 初始化颜色表
    Component.onCompleted: {
        initColorList()
    }
    
    // 初始化颜色表（根据线性渐变色条）
    function initColorList() {
        var colors = []
        // 创建渐变颜色映射：blue -> cyan -> green -> yellow -> red
        for (var i = 0; i < 256; i++) {
            var ratio = i / 255.0
            var r, g, b
            
            if (ratio < 0.4) {
                // blue (0-0.4)
                r = 0
                g = 0
                b = 255
            } else if (ratio < 0.5) {
                // blue -> cyan (0.4-0.5)
                var t = (ratio - 0.4) / 0.1
                r = 0
                g = Math.floor(255 * t)
                b = 255
            } else if (ratio < 0.6) {
                // cyan -> green (0.5-0.6)
                var t = (ratio - 0.5) / 0.1
                r = 0
                g = 255
                b = Math.floor(255 * (1 - t))
            } else if (ratio < 0.8) {
                // green -> yellow (0.6-0.8)
                var t = (ratio - 0.6) / 0.2
                r = Math.floor(255 * t)
                g = 255
                b = 0
            } else {
                // yellow -> red (0.8-1.0)
                var t = (ratio - 0.8) / 0.2
                r = 255
                g = Math.floor(255 * (1 - t))
                b = 0
            }
            
            // 计算透明度
            var alpha = Math.floor(heatAlpha / 255.0 * i)
            // 格式：#AARRGGBB
            var colorStr = "#" + 
                ("00" + alpha.toString(16)).slice(-2) +
                ("00" + r.toString(16)).slice(-2) +
                ("00" + g.toString(16)).slice(-2) +
                ("00" + b.toString(16)).slice(-2)
            colors.push(colorStr)
        }
        colorList = colors
    }
    
    // 添加热点
    function addPoint(x, y, r) {
        // 检查是否已存在该点
        var found = false
        for (var i = 0; i < points.length; i++) {
            if (points[i].x === x && points[i].y === y) {
                points[i].count++
                found = true
                break
            }
        }
        
        if (!found) {
            points.push({x: x, y: y, radius: r, count: 1})
        }
        
        // 更新最大权重
        var totalCount = 0
        for (var j = 0; j < points.length; j++) {
            if (points[j].x === x && points[j].y === y) {
                totalCount = points[j].count
                break
            }
        }
        
        if (totalCount > maxCount) {
            maxCount = totalCount
        }
        
        // 重新绘制
        canvas.requestPaint()
    }
    
    // 清空所有热点
    function clear() {
        points = []
        maxCount = 1
        canvas.requestPaint()
    }
    
    // 绘制网格背景
    Canvas {
        id: gridCanvas
        anchors.fill: parent
        z: 0
        
        onPaint: {
            var ctx = getContext("2d")
            ctx.strokeStyle = "#000000"
            ctx.lineWidth = 2
            
            // 绘制垂直线
            for (var x = 0; x <= width; x += 50) {
                ctx.beginPath()
                ctx.moveTo(x, 0)
                ctx.lineTo(x, height)
                ctx.stroke()
            }
            
            // 绘制水平线
            for (var y = 0; y <= height; y += 50) {
                ctx.beginPath()
                ctx.moveTo(0, y)
                ctx.lineTo(width, y)
                ctx.stroke()
            }
        }
    }
    
    // 绘制热力图
    Canvas {
        id: canvas
        anchors.fill: parent
        z: 1
        
        onPaint: {
            var ctx = getContext("2d")
            
            // 清空画布
            ctx.clearRect(0, 0, width, height)
            
            if (points.length === 0 || maxCount === 0) {
                return
            }
            
            // 创建权重表（用于alpha叠加）
            var weightTable = []
            for (var initY = 0; initY < height; initY++) {
                weightTable[initY] = []
                for (var initX = 0; initX < width; initX++) {
                    weightTable[initY][initX] = 0
                }
            }
            
            // 计算每个像素的权重值（径向渐变叠加）
            for (var i = 0; i < points.length; i++) {
                var pt = points[i]
                var centerX = pt.x
                var centerY = pt.y
                var r = pt.radius
                var count = pt.count
                
                // 遍历热点范围内的所有像素
                for (var y = Math.max(0, centerY - r); y <= Math.min(height - 1, centerY + r); y++) {
                    for (var x = Math.max(0, centerX - r); x <= Math.min(width - 1, centerX + r); x++) {
                        var dx = x - centerX
                        var dy = y - centerY
                        var dist = Math.sqrt(dx * dx + dy * dy)
                        
                        if (dist <= r) {
                            // 计算径向渐变的alpha值（从中心到边缘：1 -> 0）
                            var alphaRatio = 1 - (dist / r)
                            weightTable[y][x] += count * alphaRatio
                        }
                    }
                }
            }
            
            // 找到最大权重值
            var maxWeight = 0
            for (var findY = 0; findY < height; findY++) {
                for (var findX = 0; findX < width; findX++) {
                    if (weightTable[findY][findX] > maxWeight) {
                        maxWeight = weightTable[findY][findX]
                    }
                }
            }
            
            // 根据权重值绘制热力图
            if (maxWeight > 0) {
                for (var drawY = 0; drawY < height; drawY++) {
                    for (var drawX = 0; drawX < width; drawX++) {
                        var weight = weightTable[drawY][drawX]
                        if (weight > 0) {
                            // 将权重转换为alpha值（0-255）
                            var alpha = Math.floor(weight / maxWeight * 255)
                            // 根据alpha值从颜色表获取颜色
                            var color = colorList[alpha]
                            ctx.fillStyle = color
                            ctx.fillRect(drawX, drawY, 1, 1)
                        }
                    }
                }
            }
        }
    }
    
    // 鼠标点击事件
    MouseArea {
        anchors.fill: parent
        onClicked: {
            addPoint(mouseX, mouseY, radius)
        }
    }
}

